package com.mazong.serversecaa.security;

import com.mazong.serversecaa.IDbSecurityMapper;
import com.mazong.serversecaa.pojo.TbRole;
import com.mazong.serversecaa.pojo.TbRolePermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
@Component
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    IDbSecurityMapper iDbSecurityMapper;

    private HashMap<String, Collection<ConfigAttribute>> mapRoles = null;

    //-- 是否支持自定义权限
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    //-- url权限判断
    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //--1 获取用户访问的URL
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        log.info("requestUrl={}", requestUrl);

        //--2 加载角色和权限
        if(mapRoles == null || mapRoles.size() <=0 ) {
            loadRoleAndPermission();
        }

        //--3 根据url查找需要的全
        HttpServletRequest request = ((FilterInvocation) o).getRequest();
        Iterator<String> it = mapRoles.keySet().iterator();
        while(((Iterator) it).hasNext()) {
            String url = it.next();
            if(new AntPathRequestMatcher(url).matches(request)) {
                log.info("find,url={}", url);
                return mapRoles.get(url);
            }
        }

        //--4 放过
        log.info("sorry,not find url={}", requestUrl);
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    //-- 从数据库中加在权限
    public void loadRoleAndPermission() {
        if(mapRoles != null) {
            return;
        }

        //
        mapRoles = new HashMap<>();
        List<TbRolePermission> permissions = iDbSecurityMapper.getRolePermissons();
        for(TbRolePermission permission : permissions) {
            String url = permission.getUrl();
            String roleName = permission.getRoleName();

            ConfigAttribute role = new SecurityConfig(roleName);
            if(mapRoles.containsKey(url)) {
                mapRoles.get(url).add(role);
            }
            else {
                List<ConfigAttribute> list = new ArrayList<>();
                list.add(role);
                mapRoles.put(url, list);
            }
        }
    }
}
